package pecan.start;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.net.InetSocketAddress;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import pecan.core.client.GameClient;
import pecan.core.client.ResponseListener;
import pecan.core.dispatch.Response;

/**
 *
 * @author zuojie.x
 * @date 2012-8-9 下午4:15:17
 */
public class GameClientBootstrap {
	private JFrame frame;
	private JTextField accountField;
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					GameClientBootstrap window = new GameClientBootstrap();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	public GameClientBootstrap() {
		connect();
		initialize();
	}
	
	private void connect() {
		Client.client = GameClient.connect(new InetSocketAddress("127.0.0.1", 9000));
		if (Client.client == null) {
			// 失败
			JOptionPane.showMessageDialog(null, "连接服务器失败.");
			System.exit(0);
		}
	}
	
	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 600, 400);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		accountField = new JTextField();
		accountField.setBounds(190, 163, 188, 21);
		frame.getContentPane().add(accountField);
		accountField.setColumns(10);
		
		JButton startButton = new JButton("New button");
		startButton.setBounds(388, 162, 93, 23);
		frame.getContentPane().add(startButton);
		startButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String account = accountField.getText();
				Client.client.send(1, new Serializable[] {account}, new ResponseListener() {
					@Override
					public void messageReceived(Response response) {
						System.out.println(response);
					}
				});
			}
		});
	}
}
